package com.woniu.zsd.common.util;

import org.apache.tika.detect.Detector;
import org.apache.tika.io.TikaInputStream;
import org.apache.tika.metadata.Metadata;
import org.apache.tika.mime.MediaType;
import org.apache.tika.parser.AutoDetectParser;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.util.Arrays;
import java.util.List;

public class CommonUtils {
    /**
     * 通过mime类型判断文件是否为图片
     * @param file
     */
    public static boolean isImage(MultipartFile file) throws IOException {
        AutoDetectParser parser = new AutoDetectParser();
        Detector detector = parser.getDetector();
        Metadata metadata = new Metadata();
        TikaInputStream stream = TikaInputStream.get(file.getInputStream());
        MediaType mediaType = detector.detect(stream, metadata);
        return mediaType.getType().equals("image");
    }

    /**
     * 获取文件名的扩展名
     * @param filename 文件名
     * @return 文件的扩展名
     */
    public static String getFileExtension(String filename) {
        if (filename == null || filename.lastIndexOf(".") == -1) {
            return null;
        }
        return filename.substring(filename.lastIndexOf(".") + 1);
    }

    /**
     * 分割以,分割的字符串
     * @param string
     * @return
     */
    public static List<String> splitUrls(String string) {
        if (string == null || string.isEmpty()) {
            return null;
        }
        return Arrays.asList(string.split(","));
    }

    /**
     * 根据身份证号返回性别
     */
    public static Integer getGenderByIdCard(String idCardNumber) {
        int gender = Integer.parseInt(idCardNumber.substring(16, 17));
        return gender % 2 == 0 ? 2 : 1;
    }

    /**
     * 根据身份证号返回年龄
     */
    public static Integer getAgeByIdCard(String idCardNumber) {
        LocalDate date = LocalDate.parse(idCardNumber.substring(6, 14), DateTimeFormatter.ofPattern("yyyyMMdd"));
        return Period.between(date, LocalDate.now()).getYears();
    }
}
